package com.tsfyun.scm.security.config;


import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

@Configuration
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private TokenAuthorizationFilter tokenAuthorizationFilter;

    @Autowired
    private PermitUrlProperties permitUrlProperties ;

    @Autowired(required = false)
    private AuthenticationFailureHandler authenticationFailureHandler;

    @Override
    public void configure(WebSecurity web) {
        //可以考虑把这部分不需要登录的改成配置化，这样其他需要用到的地方会少好很多冗余代码
        web.ignoring().antMatchers("/v2/api-docs", "/configuration/ui", "/swagger-resources", "/configuration/security",
                "/swagger-ui.html", "/webjars/**", "/doc.html", "/login.html");
        web.ignoring().antMatchers("/favicon.ico");
        web.ignoring().antMatchers("/js/**");
        web.ignoring().antMatchers("/css/**");
        web.ignoring().antMatchers("/health");
        web.ignoring().antMatchers("/static/**");
        //验证码
        web.ignoring().antMatchers("/validata/code/**");
        //短信
        web.ignoring().antMatchers("/sms/**");
        //登录
        web.ignoring().antMatchers("/auth/login");
        //注册
        //可以直接用配置文件
        web.ignoring().antMatchers(permitUrlProperties.getIgnored());
    }

    /**
     * 考虑到第三方登录实现需要深度研究，暂不采取实现UserDetailsService接口
     * @param http
     * @throws Exception
     */
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.cors().and().csrf().disable();
        http.authorizeRequests().anyRequest().authenticated();
        http.formLogin().failureHandler(authenticationFailureHandler);
        //授权失败
        http.exceptionHandling().authenticationEntryPoint(new UnauthorizedEntryPoint());
        http.addFilterBefore(tokenAuthorizationFilter, UsernamePasswordAuthenticationFilter.class);
        http.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
        http.headers().frameOptions().disable();
        http.headers().cacheControl();

    }

}
